package ui.activity.profit;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Utils.SharedPrefStore;
import base.BaseAct;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import coom.MyType;
import event.CloseActEvent;
import event.NetErrorEvent;
import ui.activity.profit.biz.CustomerBiz;
import ui.activity.profit.component.DaggerCustomerComponent;
import ui.activity.profit.contract.CustomerContract;
import ui.activity.profit.module.CustomerModule;
import ui.activity.profit.presenter.CustomerPresenter;
import ui.adapter.CustomerAdapter;
import ui.model.MessageBean;
import ui.model.MessageReadBean;
import ui.model.OnLineBean;
import util.CommonViewUtil;
import util.LogUtils;
import util.SysUtils;
import util.stomp.StompClientUtil;
import widget.ClearEditText;
import widget.MarqueeTextView;

public class CustomerAct extends BaseAct implements CustomerContract.View {

    @Inject
    CustomerPresenter presenter;
    @Inject
    CustomerBiz biz;

    @BindView(R.id.needsx)
    TextView needsx;
    @BindView(R.id.pull_refresh_rv)
    RecyclerViewFinal rv;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.customer_input)
    ClearEditText input;
    @BindView(R.id.customer_send)
    TextView send;
    @BindView(R.id.marqueetext)
    MarqueeTextView marqueetext;

    CustomerAdapter adp;

    SharedPrefStore store;
    String realName;
    String phone;
    String sendUrl;

    String path;

    String customId;



    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        setContentView(R.layout.activity_customer);
    }

    @Override
    protected void setup() {
        DaggerCustomerComponent.builder().customerModule(new CustomerModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.lang_customer), "");
        presenter.setBiz(biz);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        CommonViewUtil.setDarw(needsx, this, R.mipmap.ic_delete, -1,
                -1, -1);
        store = new SharedPrefStore();
        customId = store.getString("id", "0");
        realName = store.getString("realname", "");
        phone = store.getString("phonenumber", "");
        path = store.getString("headImage", "");
        sendUrl = "/app/v1/customer";
        if (!StompClientUtil.IsOpen()) {
//            StompClientUtil.ConnectStomp(CustomerAct.this, customId, Constants.CONNECT_URL, "/topic/customer/" + realName + "-" + phone);
        }
        //布局
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setItemAnimator(new DefaultItemAnimator());
//        rv.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        rv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
            }
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getDateBase(true, true);
            }
        });
        ptr.autoRefresh(true);

        RxView.clicks(send)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> StompClientUtil.SendInfo(sendUrl, customId, input.getText().toString().trim(), realName, phone));
        RxView.clicks(needsx)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    if (adp.getData().size() > 0) {
                        for (int i = 0; i < adp.getData().size(); i++) {
                            StompClientUtil.ConnectDB(CustomerAct.this).deleteOldPerson(adp.getData().get(i));
                        }
                        adp.getData().clear();
                        adp.notifyDataSetChanged();
                        showMsg("删除消息记录成功");
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseActEvent(CloseActEvent event) {
        if (event.getType() == MyType.ReceiveMessage) {
            getDateBase(false, false);
        } else if (event.getType() == MyType.SendMessage) {
            input.setText("");
            input.setHint("请输入...");
            getDateBase(false, false);
        }
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }

    @Override
    public void upDateUI(OnLineBean isOnline) {
        showMsg(isOnline.getTip());
        if (adp.getData().size() == 0) {
            addCustomer(isOnline);
        } else {
            try {
                MessageBean messageBean = adp.getData().get(adp.getData().size() - 1);
                if ((!messageBean.getContentInfo().equals("您好，请问有什么可以帮助您的？") || !messageBean.getContentInfo().equals("客服暂不在线，您可以留言。" + isOnline.getTip())) &&
                        !SysUtils.sf1.format(messageBean.getTimeInfo()).equals(SysUtils.sf1.format(System.currentTimeMillis()))) {
                    addCustomer(isOnline);
                }
            } catch (Exception e) {

            }
        }
        marqueetext.setFocusable(true);
        marqueetext.setMarqueeEnable(true);
    }

    @Override
    public void upDataMessage(List<MessageReadBean> beans) {
        List<MessageBean> list = new ArrayList<>();
        if (beans.size() > 0) {
            for (int i = 0; i < beans.size(); i++) {
                MessageBean bean = new MessageBean();
                bean.setMessageType(0);
                bean.setType("0");
                bean.setContentInfo(beans.get(i).getContent());
                bean.setSignInfo(beans.get(i).getSign());
                bean.setToInfo(realName + "-" + phone);
                bean.setFromInfo("service");
                bean.setTimeInfo(System.currentTimeMillis());
                bean.setUserId(customId);
                StompClientUtil.ConnectDB(CustomerAct.this).add(bean);
                list.add(bean);
            }
        }

        if (adp == null) {
            adp = new CustomerAdapter(CustomerAct.this, list, path);
            rv.setAdapter(adp);
        } else {
            adp.getData().addAll(list);
            adp.notifyDataSetChanged();
        }
    }

    private void addCustomer(OnLineBean isOnline) {
        String sign = phone + "-" + System.currentTimeMillis();
        MessageBean messageBean = new MessageBean();
        messageBean.setContentInfo(isOnline.isOnline() ? "您好，请问有什么可以帮助您的？" : "客服暂不在线，您可以留言。" + isOnline.getTip());
        messageBean.setFromInfo("service");
        messageBean.setMessageType(0);
        messageBean.setToInfo(realName + "-" + phone);
        messageBean.setSignInfo(sign);
        messageBean.setTimeInfo(System.currentTimeMillis());
        messageBean.setType("0");
        messageBean.setUserId(customId);
        StompClientUtil.ConnectDB(CustomerAct.this).add(messageBean);
        getDateBase(false, false);
    }

    /**
     * 查询数据库
     *
     * @param isFirst
     */
    private void getDateBase(boolean isFirst, boolean isGet) {
        try {
            List<MessageBean> list = StompClientUtil.ConnectDB(CustomerAct.this).query(customId);
            LogUtils.d("result-------" + list.size());
            if (adp == null) {
                adp = new CustomerAdapter(CustomerAct.this, list, path);
                rv.setAdapter(adp);
            } else {
                adp.setDatas(list);
                adp.notifyDataSetChanged();
            }
            if (adp.getData().size() > 0) {
                rv.scrollToPosition(adp.getItemCount() - 1);
            }
            if (isFirst) {
                ptr.onRefreshComplete();
//            rv.onLoadMoreComplete();
                rv.setHasLoadMore(false);
            }
            if (isGet) {
                presenter.getInfo();
                presenter.getReadMessage(realName + "-" + phone);
            }
        } catch (Exception e) {

        }

    }
}
